# TODO: To average tiff file
# 
# Author: phamha
###############################################################################


library(raster)
library(stringr)
library(RPostgreSQL)
dr=dbDriver("PostgreSQL")

str_dbname="fimo"
str_host="192.168.3.4"
str_port=5432
str_user="rasdaman"
str_password="rasdaman"

group_query="select * from ((SELECT substr(filename,11,7) as str_date from apom.satresampmod04_daily) union (SELECT substr(filename,11,7) as str_date from apom.satresampmyd04_daily)) as total order by str_date"

con=dbConnect(dr,dbname=str_dbname,host=str_host,port=str_port,user=str_user,password=str_password)
list_date=dbGetQuery(con,group_query)

for (index in 1:nrow(list_date)) {
	date=list_date[index,1]
	year=substr(date,1,4)
	mod_file=paste("/var/www/html/fimo/apom/Resample/SatResampMOD04_Daily/",year,"/MOD04_L2.A",date,"/MOD04_L2.A",date,"_DT_10km.tif",sep="")
	myd_file=paste("/var/www/html/fimo/apom/Resample/SatResampMYD04_Daily/",year,"/MYD04_L2.A",date,"/MYD04_L2.A",date,"_CB_10km.tif",sep="")

	stack_raster=stack()
	if(file.exists(mod_file)){
		stack_raster=addLayer(stack_raster,mod_file)
	}
	if(file.exists(myd_file)){
		stack_raster=addLayer(stack_raster,myd_file)
	}
	
	daily_raster=mean(stack_raster,na.rm=TRUE)
	
	save_path=paste("/var/www/html/fimo/apom/Resample/SatResampAll04_Daily/",year,"/",date,sep="")
	#save_path=substr(list_full_name[1],1,52)
	
	out_file=paste(save_path,"/",date,"_DT_10km.tif",sep="")
	dir.create(save_path,recursive = TRUE)
	writeRaster(daily_raster,filename=out_file,format="GTiff")
	
	
}




